package com.atguigu.daijia.order.handle;

import com.atguigu.daijia.order.service.OrderInfoService;
import jakarta.annotation.PostConstruct;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

//监听器：监听延迟队列
@Component
public class RedisDelayHandle {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private OrderInfoService orderInfoService;

    //监听
    @PostConstruct//bean注册后才执行
    public void listener() {
        //死循环监听
        new Thread(()->{
            while (true){
                //获取延迟队列里面的阻塞队列
                RBlockingQueue<String> blockingQueue = redissonClient.getBlockingQueue("queue_cancel");

                //从队列中获取消息
                try {
                    String orderId = blockingQueue.take();
                    //如果捕获到消息，说明订单已经15分钟没有被消费了，直接取消订单
                    if(StringUtils.hasText(orderId)){
                        orderInfoService.orderCansel(Long.parseLong(orderId));
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }
}
